<template>
    <view class="i-gesture" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
        <slot />
    </view>
</template>

<script setup lang="ts">
const emits = defineEmits(["left", "right"]);

let startX = 0,
    startY = 0;

let moveX = 0,
    moveY = 0;

let threshold = 10;

let isSwipe = false;

/**
 * 处理触摸开始事件
 * @param {Object} event - 触摸事件对象
 * @param {Array} event.touches - 触摸点数组
 */
const onTouchStart = ({ touches }) => {
    const { clientX, clientY } = touches[0];

    startX = clientX;
    startY = clientY;

    isSwipe = true;
};

/**
 * 处理触摸移动事件
 * @param {Object} event - 触摸事件对象
 * @param {Array} event.touches - 触摸点数组
 */
const onTouchMove = ({ touches }) => {
    if (!isSwipe) return;

    const { clientX, clientY } = touches[0];

    moveX = Math.abs(clientX);
    moveY = Math.abs(clientY);

    if (moveX > threshold) {
        isSwipe = true;
    }
};

/**
 * 处理触摸结束事件，判断滑动方向并触发相应事件
 */
const onTouchEnd = () => {
    if (!isSwipe || moveX === 0 || moveY === 0) return;
    const x = moveX - startX;
    const y = moveY - startY;

    // 垂直方向滑动超过阈值则不处理
    if (y <= -20 || y >= 20) return;

    // 水平方向滑动判断
    if (x <= -70) {
        emits("left");
    } else if (x >= 70) {
        emits("right");
    }

    isSwipe = false;
    moveX = 0;
    moveY = 0;
};
</script>

